/*
db库
 */
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
const Config = require('./config.js');
const fs = require('fs');
const Grid = require('gridfs-stream');
const mongo = require('mongodb');

class Db {
    static getInstance() {  //单例
        if (!Db.instance) {
            Db.instance = new Db();
        }
        return Db.instance;
    }

    constructor(){
        this.dbClient = ""; //放db对象
        this.connect();
    }

    connect(){
        let _that = this;
        return new Promise((resolve, reject) => {
            if (!_that.dbClient) {  //解决数据库多次连接问题
                MongoClient.connect(Config.dbUrl, {useUnifiedTopology: true}, (err, client) => {
                    if (err) {
                        reject(err);
                    } else {
                        _that.dbClient = client.db(Config.dbName);
                        resolve(_that.dbClient);
                    }
                })
            } else {
                resolve(_that.dbClient);
            }
        })

    }

    find(collectionName, json){
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                var result = db.collection(collectionName).find(json);
                result.toArray((err, docs) => {
                    //console.log(docs);
                    if (err) {
                        reject(err);
                        return;
                    }
                    resolve(docs);
                })
            })
        })
    }

    findSomeCol(collectionName, json1, json2){ //查找某些列
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                var result = db.collection(collectionName).find(json1).project(json2);
                result.toArray((err, docs) => {
                    //console.log(docs);
                    if (err) {
                        reject(err);
                        return;
                    }
                    resolve(docs);
                })
            })
        })
    }

    findOne(collectionName, json){
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                var result = db.collection(collectionName).findOne(json, ((err, docs) => {
                    //console.log(docs);
                    if (err) {
                        reject(err);
                        return;
                    }
                    resolve(docs);
                }));
            })
        })
    }

    update(collectionName, json1, json2){
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                db.collection(collectionName).updateOne(json1, {
                    $set: json2
                }, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }

    insert(collectionName, json){
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                db.collection(collectionName).insertOne(json, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }

    insert2(collectionName, json){
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                db.collection(collectionName).insertMany(json, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }

    remove1(collectionName, json){
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                db.collection(collectionName).removeOne(json, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }

    remove2(collectionName, json){
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                db.collection(collectionName).deleteMany(json, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }

    count(collectionName, json){
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                db.collection(collectionName).countDocuments(json, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }

    getObjectId(id) {   //字符串转化为对象
        return new ObjectID(id);
    }

    uploadFile(path, filename){  //gridfs上传文件
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                var bucket = new mongo.GridFSBucket(db);
                fs.createReadStream(path).
                pipe(bucket.openUploadStream(filename)).
                on('error', function(error) {
                    reject(error);
                }).
                on('finish', function(result) {
                    resolve(result);
                });
            })
        })
    }

    downloadFile(fileId, path){  //gridfs下载文件
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                var bucket = new mongo.GridFSBucket(db);
                bucket.openDownloadStream(fileId).
                pipe(fs.createWriteStream(path)).
                on('error', function(error) {
                    reject(error);
                }).
                on('finish', function() {
                    resolve(1);
                });
            })
        })
    }

    addArray(collectionName, json1, json2){ //数组添加元素
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                db.collection(collectionName).updateOne(json1, {
                    $addToSet: json2
                }, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }

    deleteArray(collectionName, json1, json2){  //数组删除元素
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                db.collection(collectionName).updateOne(json1, {
                    $pull: json2
                }, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }

    autoIncrease(json){
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                db.collection("atlas").updateOne(json, {
                    $inc: {count: 1}
                }, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }

    autoReduce(json){
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                db.collection("atlas").updateOne(json, {
                    $inc: {count: -1}
                }, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }
}
module.exports = Db.getInstance();

// 测试
// var myDb = new Db();
// myDb.find("project", {"_id": "1"}).then(data => {
//     console.log(data.length);
// })


// const MongoClient = require('mongodb').MongoClient;
//
// MongoClient.connect(
//     Config.dbUrl,
//     {
//         useNewUrlParser: true,
//         useUnifiedTopology: true,
//         minPoolSize: 3,  //会初始化3个查询语句的连接，一共4个连接
//         maxPoolSize: 10
//     },
//     function(err, client) {
//
//         global.db = client.db();
//
//     }
// )
